<template>
    <div>
      <el-container style="height:623px;">
        <!-- 左侧树形结构 -->
        <el-aside width="150px" id="div_tree">
          <div class="aside">
            <a-tree :tree-data="treeData" showIcon show-line default-expand-all @select="onSelect" @onExpand="onExpand">
              <a-icon slot="folder" type="folder" theme="filled" :style="{ color: '#f4ea2a' }" />
              <a-icon slot="file" type="file" />
              <template #title="{ key: treeKey, title, type}">
                <a-dropdown :trigger="['contextmenu']">
                  <span>{{ title }}</span>
                  <template #overlay>
                    <a-menu @click="({ key: menuKey }) => onContextMenuClick(treeKey, menuKey, type)" id="div_menu">
                      <a-menu-item key="1"><a-icon type="folder" :style="{fontSize:'16px'}" />新建目录</a-menu-item>
                      <a-menu-item key="2"><a-icon type="database" :style="{fontSize:'16px'}" theme="filled" />新建表</a-menu-item>
                      <a-menu-item key="3"><a-icon type="edit" :style="{fontSize:'16px'}" theme="filled" />编辑</a-menu-item>
                      <a-menu-item key="4"><a-icon type="delete" :style="{fontSize:'16px'}" theme="filled" />删除</a-menu-item>
                    </a-menu>
                  </template>
                </a-dropdown>
              </template>
            </a-tree>
          </div>
        </el-aside>
        <!-- 右侧容器布局-->
        <el-container>
          <!-- 右侧内容组件 -->
          <el-main style="padding:0px;">
            <div style="margin-bottom: 2px;padding-left: 10px;">
              <el-button type="primary" size="small" @click="addRow">新建</el-button>
              <el-button type="primary" size="small">保存</el-button>
              <el-button type="primary" size="small">批量删除</el-button>
            </div>
            <el-table :data="sysTableInfos" size="mini" height="560"   :border="true"  >
              <el-table-column type="selection" width="35" align="center"></el-table-column>
              <el-table-column label="序号" width="50" type="index" align="center"></el-table-column>
              <el-table-column label="字段名称" width="150" prop="columnName" align="center">
                <template slot-scope="scope">
                  <el-input size="small" v-if="scope.row.isEdit" v-model="scope.row.columnName"></el-input>
                  <span v-else>{{scope.row.columnName}}</span>
                </template>
              </el-table-column>
              <el-table-column label="字段描述" width="150" prop="comment" align="center">
                <template slot-scope="scope">
                  <el-input size="small" v-if="scope.row.isEdit" v-model="scope.row.comment"></el-input>
                  <span v-else>{{scope.row.comment}}</span>
                </template>
              </el-table-column>
              <el-table-column label="字段类型" width="110" prop="columnType" align="center">
                <template slot-scope="scope">
                    <el-select size="small" v-if="scope.row.isEdit" v-model="scope.row.columnType" placeholder="请选择" clearable>
                     <el-option
                         v-for="item in columnType"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value"
                         :disabled="item.disabled">
                       </el-option>
                     </el-select>
                     <span v-else>{{scope.row.columnType}}</span>
                </template>
              </el-table-column>
              <el-table-column label="字段长度" width="100" prop="length" align="center">
                 <template slot-scope="scope">
                   <el-input v-if="scope.row.isEdit" size="small" v-model="scope.row.length" controls-position="right" :min="1" :max="10"></el-input>
                   <span v-else>{{scope.row.length}}</span>
                 </template>
              </el-table-column>
              <el-table-column label="默认值" width="150" prop="defaultValue" align="center">
                <template slot-scope="scope">
                  <el-input size="small" v-if="scope.row.isEdit" v-model="scope.row.defaultValue" />
                  <span v-else>{{scope.row.defaultValue}}</span>
                </template>
              </el-table-column>
              <el-table-column label="键信息" width="110" prop="columnKey" :formatter="formatter" align="center">
                <template slot-scope="scope">
                    <el-select size="small" v-if="scope.row.isEdit" v-model="scope.row.columnKey" placeholder="请选择" clearable>
                     <el-option
                         v-for="item in columnKeyType"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value"
                         :disabled="item.disabled">
                       </el-option>
                     </el-select>
                     <span v-else>{{scope.row.columnKey == 'PRI' ? '主键' : ''}}</span>
                </template>
              </el-table-column>
              <el-table-column label="扩展信息" width="110" prop="extra" :formatter="formatter" align="center">
                <template slot-scope="scope">
                    <el-select size="small" v-if="scope.row.isEdit" v-model="scope.row.extra" placeholder="请选择" clearable>
                     <el-option
                         v-for="item in extraType"
                         :key="item.value"
                         :label="item.label"
                         :value="item.value"
                         :disabled="item.disabled">
                       </el-option>
                     </el-select>
                     <span v-else>{{scope.row.extra == 'AUTO_INCREMENT' ? '自增' : ''}}</span>
                </template>
              </el-table-column>
              <el-table-column label="系统字段" width="80" prop="system" :formatter="formatter" align="center"></el-table-column>
              <el-table-column label="排序" width="60" prop="sort" align="center"></el-table-column>
              <el-table-column label="操作" width="180" prop="operate" align="center" fixed="right">
                <template slot-scope="scope">
                  <el-row :gutter=2>
                  <el-col :span=8 v-if="!scope.row.isEdit">
                    <el-link icon="el-icon-edit" type="primary" @click="edit(scope.$index)">编辑</el-link>
                  </el-col>
                  <el-col :span=8 v-if="scope.row.isEdit">
                    <el-link icon="el-icon-refresh-left" type="default" @click="cancelEdit(scope.row.id)">取消</el-link>
                  </el-col>
                  <el-col :span=8>
                    <el-link icon="el-icon-delete" type="warning" @click="saveRow(scope.row.id)">保存</el-link>
                  </el-col>
                  <el-col :span=8>
                    <el-link icon="el-icon-delete" type="danger" @click="deleteRow(scope.$index)">删除</el-link>
                  </el-col>
                </el-row>
                </template>
              </el-table-column>
            </el-table>
          </el-main>
          <!-- 底部分页 -->
          <el-footer style="height:30px;" >
            <!-- <el-pagination
                background
                layout="total,sizes, prev, pager, next"
                :total="pagination.total"
                :current-page="pagination.currentPage"
                :page-size="pagination.pageSize"
                :page-sizes="pageSizes"
             @current-change="currentChange"
                @size-change="pageSizeChange"
            >
            </el-pagination> -->
             <el-row>
               <el-col :span="2">
                <el-link  icon="el-icon-top">上移</el-link>
               </el-col>
               <el-col :span="2">
                <el-link  icon="el-icon-bottom">下移</el-link>
               </el-col>
             </el-row>
          </el-footer>
        </el-container>
      </el-container>

      <!--dialog弹窗创建目录或表-->
      <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="30%" @close="closeDialog">
            <el-form id="form" :inline="false" :model="sysTable" class="demo-form-inline el-form" size="mini" label-width="60px" label-position="right">
              <el-row>
                <el-col :span="12" :xs="24">
                  <el-form-item :label="sysTable.type==0?'目录名':'表名'">
                    <el-input size="small" v-model="sysTable.tableName" :placeholder="sysTable.type==0?'目录名':'表的业务名称'"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12" :xs="24">
                  <el-form-item label="表编码">
                    <el-input size="small" v-model="sysTable.tableCode" placeholder="表编码与真实表名一致"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="24" :xs="6">
                  <el-form-item label="描述">
                    <el-input size="small" type="textarea" v-model="sysTable.remark" placeholder="填写描述信息便于业务理解"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="6" :offset="8" :xs="24">
                  <el-button size="small" type="primary" @click="saveSysTable">取消</el-button>
                </el-col>
                <el-col :span="6" :xs="24">
                  <el-button size="small" type="primary" @click="saveSysTable">保存</el-button>
                </el-col>
              </el-row>

            </el-form>
            </el-dialog>
    </div>
</template>

<script>
import Vue from 'vue';
import {Button,Icon,Tree,Dropdown,Menu,Layout,Form,Input,Slider} from 'ant-design-vue';
import service from '../../config/utils/service.js';
import cache from '../../config/utils/cache.js';
let antd = {Button,Icon,Tree,Dropdown,Menu,Layout,Form,Input,Slider}
Object.keys(antd).forEach(v => {
  Vue.use(antd[v]);
});
Vue.config.productionTip = false
export default {
    name: 'TableManage',
    data() {
        return {
          treeData: [], // 左侧树形数据
          sysTable: {}, // 当前选中目录或表信息
          sysTableOld: {}, // sysTable的备份数据，当新建目录/表时，sysTable -> sysTableOld, sysTable -> {}，取消/关闭: sysTable = SysTableOld
          sysTableInfos: [], // 当前表对应的表详细信息（table绑定数据）
          sysTableInfosHistory: [], // sysTableInfos的备份
          pagination:{ // 分页信息
            total: 0, // 数据总量
            currentPage: 1, // 当前页
            pageSize: 20 // 分页大小
          },
          pageSizes: [20, 50, 100, 200], // 分页大小项目
          dialogVisible: false, // 是否显示创建目录或表的弹框
          createType: 0, // 创建目录还是表（0：创建目录，1：创建表）
          dialogTitle: '新建表', // dialog的标题（0：新建目录，1：新建表，2：编辑）
          columnType: [], // 字段类型字典项
          columnKeyType: [{value:'PRI',label:'主键'},{value:'FRI',label:'外键','disabled':true}], // 主外键下拉选，暂不支持外键
          extraType: [{value:'AUTO_INCREMENT',label:'自增'}], // 字段额外信息下拉选（例如：自增）
          
        }
    },

    methods: {
      // 树形节点选中事件
      async onSelect(id, info) {
        console.log("id: " + id + " info: " );
        console.log(info);
        if(!info.selected){
          console.log('取消选中树形节点');
          return;
        }
        let data = await service.get('/sys/table/' + id);
        this.sysTable = data;
        this.sysTableOld = JSON.parse(JSON.stringify(this.sysTable));
        //console.log(data);
        // 如果当前选中的是表，查询表的详细信息
        if (data.type == "1") {
          let tableInfo = await service.get('/sys/tableinfo/select/' + id);
          // 初始化每行数据的编辑状态（未编辑）、是否改变状态（未改变）
          tableInfo.forEach(item => {
            item['isEdit']=false;
            item['changed']=false;
          });
          // 保存到table绑定的数据
          this.sysTableInfos = tableInfo;
          // 数组拷贝（使用js数组深拷贝，保证原数组修改后，不会影响备份数据）JSON.parse(JSON.stringify(arr));
          this.sysTableInfosHistory = JSON.parse(JSON.stringify(this.sysTableInfos));
        }
      },
      // 树形展开事件
      onExpand() {


        console.log('Trigger Expand');
      },
      // 树形右键事件(treeKey:id,menuKey:操作菜单的序号，type:当前节点类型)
      onContextMenuClick(treeKey, menuKey, type){
        console.log("treeKey: " + treeKey + " menuKey: " + menuKey + " type: " + type);
        // 如果当前选中节点类型是表，且操作类型是创建目录或表，不允许操作
        if(type==1 && (menuKey==1 || menuKey==2)) {
            this.$message.error('只能选中目录进行创建哟！');
          return;
        }
        console.log(treeKey + '  ' + menuKey + '  ' + type);
        // 当前右键树形菜单的操作项
        this.createType = menuKey;
        // 如果是新建操作，清空sysTable
        if((menuKey == 1 || menuKey == 2)){
          this.sysTableOld = JSON.parse(JSON.stringify(this.sysTable));
          this.sysTable = {type:type,parentId:treeKey};
        }
        // 如果是新建或编辑操作，展示dialog弹框
        if((menuKey == 1 || menuKey == 2 || menuKey == 3)) {
          switch (menuKey) {
            case "1": this.dialogTitle = "新建目录"; break;
            case "2": this.dialogTitle = "新建表"; break;
            case "3": this.dialogTitle = "编辑"; break;
          }

          this.dialogVisible = true;
          console.log(this.sysTable);
          return;
        }
        if(menuKey == 4){
          let msg = type == 0 ? "此操作会删除改目录及目录下数据，确认删除？" : "此操作会永久删除数据库对应表结构，确认删除？";
          this.$parent.$confirm(msg, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
        }

      },
      // 取消dialog弹窗
      closeDialog(){
        // 恢复之前的数据
        this.sysTable = JSON.parse(JSON.stringify(this.sysTableOld));
      },
      // 保存dialog弹框表单数据
      async saveSysTable(e) {
        let isCreate = this.sysTable.id ? true : false;
        // 保存数据
        let back = await service.post('/sys/table/save', this.sysTable);
        this.sysTable = back;
        this.sysTableOld = JSON.parse(JSON.stringify(this.sysTable));
        // 如果是新建操作，需要重新加载树形数据
        if(isCreate){
          console.log("重新加载树形数据.......")
          let data = await service.get('/sys/table/tree');
          this.treeData = data;
          console.log(this.treeData);
        }
        // 关闭dialog弹窗
        this.dialogVisible = false;
      },
      // table列格式化
      formatter(row, column, cellValue, index) {
          if (column.property == 'system') {
              if (cellValue == '1') {
                  return "是";
              } else {
                  return "否";
              }
          } else if (column.property == 'columnKey') {
              if (cellValue == 'PRI') {
                  return "主键";
              } else {
                  return "";
              }
          }else if (column.property == 'extra') {
              if (cellValue == 'AUTO_INCREMENT') {
                  return "自增";
              } else {
                  return "";
              }
          }
          return cellValue;
      },
      // table行编辑按钮
      edit(index) {
        console.log("edit index :" + index);
        let i = 0;
        this.sysTableInfos.map(item => {
          if(index == i){
            item['isEdit'] = true;
          } else {
            item['isEdit'] = false;
          }
          i++;
        });
      },
      // 取消行编辑
      cancelEdit(id) {
        // 查找到历史数据
        let history = {};
        this.sysTableInfosHistory.map(item => {
          if(item.id == id){
            history = item;
            return;
          }
        });
        // 恢复历史数据，并修改编辑状态为 “未编辑”
        this.sysTableInfos.map(info => {
          if (info.id == id) {
            Object.keys(history).map(key => {
              info[key] = history[key];
            });
            return;
          }
        })

      },
      // 保存当前行数据
      saveRow(id){
        // 修改编辑状态为"未编辑状态"
        this.sysTableInfos.map(item => {
          if(item.id == id){
            item['isEdit'] = false;
          }
        });
      },
     // 删除当前行
     deleteRow(index){
        // 删除当前索引对应数组的元素（索引，从该索引开始，删除元素的个数）
        this.sysTableInfos.splice(index, 1);
        // 重排序
        this.resort();
     },
     // 新增一行
     addRow() {
       // 取消所有编辑
       this.sysTableInfos.map(item => {
         item['isEdit'] = false;
       })
       // 数组头部添加元素，并编辑
       this.sysTableInfos.unshift({isEdit:true,system:0});
       // 重排序
       this.resort();
     },
     // 重新排序(新增、删除后重排序)
     resort() {
       let index = 0;
       this.sysTableInfos.map(item => {
         item['sort'] = index;
         index ++;
       })
     },

    },
    async beforeCreate() {
      console.log("beforeCreate........");
      // 获取左侧树形数据
      let data = await service.get('/sys/table/tree');
      this.treeData = data;
      // 尝试从本地存储中获取字段类型字典项
      let cache = localStorage.getItem("columnType");
      if(cache != null) {
        this.columnType = cache;
      } else {
        // 加载远程数据类型字典项
        let remoteData = await service.get('/sys/dictionary/view/3');
        this.columnType = remoteData;
        console.log("字典项：" + this.columnType);
      }

    },
    mounted() {

    },
    // 加载缓存数据
    async created(){
      // console.log("created: menuKey: " + this.$props.menuKey);
      // let data = cache.loadCache(this.$props.menuKey);
      // console.log("加载缓存数据.......");
      // console.log(data);
      // this.data = data;
    }
}
window.onload = function () {
  var dom = document.getElementsByClassName("ant-tree-list-holder-inner");
  console.log("dom>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
  console.log(dom);
  // document.getElementById("div_tree").oncontextmenu = function (event) {
  //   // 禁用默认的右键事件
  //   event.returnValue = false;
  //   var menu =  "<a-menu @click=\"({ key: menuKey }) => onContextMenuClick(treeKey, menuKey, type)\" id=\"div_menu\">\n" +
  //       "                             <a-menu-item key=\"1\"><a-icon type=\"folder\" :style=\"{fontSize:\\'16px\\'}\" />新建目录</a-menu-item>\n" +
  //       "                             <a-menu-item key=\"2\"><a-icon type=\"database\" :style=\"{fontSize:\\'16px\\'}\" theme=\"filled\" />新建表</a-menu-item>\n" +
  //       "                             <a-menu-item key=\"3\"><a-icon type=\"edit\" :style=\"{fontSize:\\'16px\\'}\" theme=\"filled\" />编辑</a-menu-item>\n" +
  //       "                             <a-menu-item key=\"4\"><a-icon type=\"delete\" :style=\"{fontSize:\\'16px\\'}\" theme=\"filled\" />删除</a-menu-item>\n" +
  //       "                           </a-menu>";
  //   document.getElementById("div_tree").append(menu);
  // }
}
</script>

<style scoped>
.aside {
  height: 600px;
  border-right: 1px solid lightgray;
  overflow: auto;
}

</style>
